package com.mzy.excel.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.mzy.basics.utils.Java.SystemException;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Ives
 * * @date 2022/2/9
 */

/**
 * easyExcel 分Sheet页导出工具类
 */

public class WriteExcel {
  /**
   * 传入headDataMap key为分组sheet名，
   * value为具体数据list
   *
   * @param response
   * @param headDataMap
   * @param fileName
   */
  public static void writeExcelByTable(HttpServletResponse response, Map<String, List<Object>> headDataMap, String fileName) {
    try {
      ExcelWriter excelWriter = EasyExcel.write(getOutputStream(fileName, response)).build();
      AtomicInteger tableNo = new AtomicInteger(); // 原子操作
      for (Map.Entry<String, List<Object>> entry :
              headDataMap.entrySet()) {
        String key = entry.getKey();
        WriteSheet sheet = EasyExcel.writerSheet(tableNo.get(), key.replaceAll("[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]",
                "")).head(Object.class).build();
        excelWriter.write(entry.getValue(), sheet);
        tableNo.incrementAndGet();
      }
      excelWriter.finish();
    } catch (Exception e) {
      throw new SystemException(e);
    }
  }

  private static OutputStream getOutputStream(String fileName, HttpServletResponse response) {
    String filePath = fileName + ExcelTypeEnum.XLSX.getValue();

    try {
      fileName = URLEncoder.encode(filePath, StandardCharsets.UTF_8.name());
      String contentStr = "attachment; fileName='%s';filename*=utf-8''%s";
      String contentValue = String.format(contentStr, fileName, fileName.replace("\\+", " "));
      response.setContentType("application/octet-stream");
      response.setHeader("Content-Type", "application/octet-stream");
      response.addHeader("Content-Disposition", contentValue);
      return response.getOutputStream();
    } catch (Exception var5) {
      throw new SystemException(var5);
    }
  }
}
